import cTitle from "components/title";
import { Toast } from 'vant';
import { scrollMixin } from "utils/mixin";
export default {
  mixins: [scrollMixin], //加载更多
  data() {
    return {
      datas: [],
      loading: false,
      allLoaded: false,
      goload: true,
      isLoadMore: true,
      page: 1,
      total_page: 0,
      result:[],
      kwd:'',
      store_id:'',
      show_num:'',
      chooseGoods: [],
      historicalRecord: [], //搜索记录
      inputShow: false,
      showPopup: false
    };
  },
  activated() {
    this.initData();
    if(this.$route.params.keyword!=undefined){
      this.kwd=this.$route.params.keyword;
    }
    this.store_id=this.$route.params.store_id;
    this.getNum();
    this.search();  
    this.$nextTick(() => {
      this.$refs.search_input.focus();
    })
  },
  methods: {
    getNum(){
      let that = this;
      let json = {store_id:this.store_id };
      $http
        .get(
          "plugin.store-cashier.frontend.store.near-by-goods.get-store-goods",
          json,
          "获取中"
        )
        .then(
          response => {
            if (response.result == 1) {
              that.show_num=response.data.show_num;
            } else {
              that.$dialog.alert({message:response.msg});
            
            }
          },
          function(response) {
            console.log(response);
          }
        );
    },
    initData(){
      this.datas=[];
      this.loading=false;
      this.allLoaded=false;
      this.goload=true;
      this.isLoadMore=true;
      this.page=1;
      this.total_page=0;
    },
    add(){
      let json={store_id:this.store_id,choose_goods:this.result};
      $http
        .post(
          "plugin.nearby-store-goods.frontend.controllers.goods.index",
          json,
          "获取中"
        )
        .then(
          response => {
            if (response.result == 1) {
              Toast(response.msg);
             
            } else {
              Toast(response.msg);
            }
          },
          function(response) {
            console.log(response);
          }
        );
    },
    search(value){
      if(value !== 1) {
        let getData = JSON.parse(localStorage.getItem('introduceGoodRecords_')) || [];
        this.historicalRecord = getData !== null ? [...getData,this.kwd] : [];
        this.historicalRecord = [...new Set(Array.from([...this.historicalRecord].filter(Boolean)))];
        localStorage.setItem("introduceGoodRecords_", JSON.stringify(this.historicalRecord));
      }
      // this.$refs.search_input.blur();
      this.initData();
      let that=this;
      let json={kwd:this.kwd,store_id:this.store_id,page:this.page};
      $http
        .post(
          "plugin.store-cashier.frontend.store.goods.get-goods-by-kwd",
          json,
          "获取中"
        )
        .then(
          response => {
            if (response.result == 1) {
              that.datas=response.data.data;
              that.total_page = response.data.last_page;
              for(let item of that.result) {
                for(let citem of that.datas) {
                  if(item == citem.id) {
                    that.$set(citem, "isAdd" , true);
                  }
                }
              }
              if (!that.total_page) {
                that.total_page = 0;
              }
            } else {
              Toast(response.msg);
            }
          },
          function(response) {
            console.log(response);
          }
        );
    },
    getMoreData() {
      var that = this;
      if (this.page === this.total_page) {
        return;
      }
      if (this.page >= this.total_page) {
        that.loading = true;
        that.allLoaded = true;
        return;
      } else {
        this.page = this.page + 1;
        let json ={kwd:this.kwd,store_id:this.store_id,page:this.page};
        $http
          .post(
            "plugin.store-cashier.frontend.store.goods.get-goods-by-kwd",
            json,
            "加载中"
          )
          .then(
            function(response) {
              if (response.result === 1) {
                that.loading = false;
                that.allLoaded = false;
                that.datas = that.datas.concat(response.data.data);
                for(let item of that.result) {
                  for(let citem of that.datas) {
                    if(item == citem.id) {
                      that.$set(citem, "isAdd" , true);
                    }
                  }
                }
              } else {
                that.page = that.page - 1;
                that.loading = true;
                that.allLoaded = true;
                that.isLoadMore = false;
                return;
              }
            },
            function(response) {
              // error callback
            }
          );
      }
    },
    // 选中商品
    clickAdd(index) {
      this.$set(this.datas[index],"isAdd",true);
      let newChooseGoods = this.datas.filter(item  => item.isAdd);
      this.chooseGoods = this.reduceData([...this.chooseGoods,...newChooseGoods]);
      this.result = this.chooseGoods.map(citem => citem.id);
    },
    // 删除商品
    clickDel(index,id) {
      this.$set(this.datas[index],"isAdd",false);
      let index_ = ""
      for(let [key , item] of this.chooseGoods.entries()) {
        if(item.id == id) {
          index_ = key;
        }
      }
      this.chooseGoods.splice(index_,1);
      this.result = this.chooseGoods.map(citem => citem.id);
    },
    // 删除选中的数据
    delChooseGoods(index,id) {
      this.chooseGoods.splice(index,1);
      for(let [index_ , item] of this.datas.entries()) {
        if(item.id == id) {
          this.$set(this.datas[index_],"isAdd",false);
        }
      }
      this.result = this.chooseGoods.map(citem => citem.id);
      // this.result.push(...newArr);
    },
    // 清空选中数据
    clearChooseGoods() {
      this.chooseGoods = [];
      for(let [index_ , item] of this.datas.entries()) {
        this.$set(this.datas[index_],"isAdd",false);
      }
      this.result = [];
    },
    // 过滤重复数据
    reduceData(person) {
      let obj = {};
      let peon = person.reduce((cur,next) => {
          obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
          return cur;
      },[]) //设置cur默认类型为数组，并且初始值为空的数组
      return peon
    },
    // 清除缓存
    clearHistoryData() {
      this.historicalRecord = [];
      localStorage.setItem('introduceGoodRecords_', JSON.stringify([]));
    },
    delHistoricalRecord(index) {
      this.historicalRecord.splice(index,1);
      localStorage.setItem('introduceGoodRecords_', JSON.stringify(this.historicalRecord));
    },
    // 搜索历史记录
    searchHistoricalRecord(item) {
      this.kwd = item;
      this.search(1);
    },
    searchFocusr() {
      this.inputShow = true;
    },
    searchBlur() {
      setTimeout(() => {
        this.inputShow = false;
      },100)
    }
  },
  components: {
    cTitle
  }
};
